package com.gpb.common.utils;

import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * 国际化信息帮助类
 * @author GuoPengBin
 * @dateTime Apr 15, 2014  10:30:55 AM
 */
public final class MessageResolver implements TemplateMethodModel {
	private static WebApplicationContext messageSource;
	private static Locale locale;
	/**
	 * @param request
	 */
	public MessageResolver(HttpServletRequest request){
		messageSource =WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		if (localeResolver != null) {
			locale = localeResolver.resolveLocale(request);
		} else {
			locale = request.getLocale();
		}
	}

	/**
	 * 获得国际化信息
	 * @param request HttpServletRequest
	 * @param code 国际化代码
	 * @param args 替换参数
	 * @return
	 */
	public static String getMessage(HttpServletRequest request, String code,
			Object... args) {
		try {
			messageSource =WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
			if (messageSource == null) {
				throw new IllegalStateException("WebApplicationContext not found!");
			}
			LocaleResolver localeResolver = RequestContextUtils
					.getLocaleResolver(request);
			if (localeResolver != null) {
				locale = localeResolver.resolveLocale(request);
			} else {
				locale = request.getLocale();
			}
			return messageSource.getMessage(code, args, locale);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return null;
	}


	/**
	 *TemplateMethodModel   的实现方法
	 *获取国际化标签信息 需有通过构造函数 public MessageResolver(HttpServletRequest request) 才能使用
	 */
	public Object exec(List arg0) throws TemplateModelException {
		try {
			if(arg0.size()>0){
				if(arg0.size()==1){
					return messageSource.getMessage(arg0.get(0).toString(),new Object[]{},locale);
				}else{
					Object[] objs=new Object[arg0.size()-1];
					for (int i=objs.length-1;i>=0;i--) {
						objs[i]=arg0.get(i+1);
					}
					return messageSource.getMessage(arg0.get(0).toString(),objs,locale);
				}
			}
		} catch (Exception e) {
		}
		return arg0.size()>0?arg0.get(0):null;
	}
}
